import csv
import random
import string
from datetime import datetime, timedelta
import math
from pathlib import Path


# 生成随机姓名
def generate_name():
    last_names = [
        "赵",
        "钱",
        "孙",
        "李",
        "周",
        "吴",
        "郑",
        "王",
        "冯",
        "陈",
        "褚",
        "卫",
        "蒋",
        "沈",
        "韩",
        "杨",
        "朱",
        "秦",
        "尤",
        "许",
    ]
    first_names = [
        "伟",
        "芳",
        "娜",
        "秀英",
        "敏",
        "静",
        "强",
        "磊",
        "军",
        "洋",
        "勇",
        "艳",
        "杰",
        "涛",
        "明",
        "华",
        "丽",
        "桂",
        "洁",
        "红",
    ]
    return random.choice(last_names) + random.choice(first_names)


# 生成随机身份证号
def generate_id():
    # 前6位地址码（随机选取）
    area_codes = [
        "110101",
        "110102",
        "110103",
        "310101",
        "310104",
        "440104",
        "440106",
        "510104",
        "510107",
        "610103",
    ]
    area = random.choice(area_codes)

    # 8位出生日期（2000-2005年之间）
    start_date = datetime(1980, 1, 1)
    end_date = datetime(2000, 12, 31)
    random_date = start_date + timedelta(
        days=random.randint(0, (end_date - start_date).days)
    )
    birth = random_date.strftime("%Y%m%d")

    # 3位顺序码
    seq = str(random.randint(100, 999))

    # 1位校验码（简化处理，实际有算法）
    check_code = random.choice("0123456789X")

    return area + birth + seq + check_code


# 生成随机开户银行
def generate_bank():
    banks = [
        "中国工商银行",
        "中国农业银行",
        "中国银行",
        "中国建设银行",
        "交通银行",
        "招商银行",
        "浦发银行",
        "中信银行",
        "光大银行",
        "华夏银行",
        "民生银行",
        "广发银行",
        "平安银行",
        "兴业银行",
        "浙商银行",
    ]
    return random.choice(banks)


# 生成随机借款时间（近3年）
def generate_loan_time():
    start_date = datetime(2022, 1, 1)
    end_date = datetime(2025, 11, 6)
    random_date = start_date + timedelta(
        days=random.randint(0, (end_date - start_date).days)
    )
    return random_date.strftime("%Y-%m-%d %H:%M:%S")


# 生成数据并写入CSV
file_path = Path(__file__).parent / "金融渠道账单.csv"

with open(file_path, "w", newline="", encoding="utf-8") as csvfile:
    fieldnames = ["姓名", "身份证号", "开户银行", "借款金额", "借款时间", "借款银行"]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for _ in range(1000):
        writer.writerow(
            {
                "姓名": generate_name(),
                "身份证号": generate_id(),
                "开户银行": generate_bank(),
                "借款金额": math.floor(random.random() * 10000),
                "借款时间": generate_loan_time(),
                "借款银行": generate_bank(),  # 借款银行与开户银行可相同或不同
            }
        )

print("CSV文件生成成功，文件名为：金融渠道账单.csv")
